//
//  OEHomeViewController.m
//  OneEightyNine
//
//  Created by apple on 2019/3/6.
//  Copyright © 2019 stoneobs. All rights reserved.
//

#import "OEHomeViewController.h"
#import "OEHomeCollectionReusableHeader.h"
#import "OELocationViewController.h"
#import "OEHomeCollectionViewCell.h"
#import "OEHotBunessViewController.h"
#import "OEHotOfferViewController.h"
#import "OEPaymentSettingViewController.h"
@interface OEHomeViewController ()
<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
@property(nonatomic, strong) OEHomeModel                     *homeModel;/**<  */
@property(nonatomic, strong) UICollectionView                     *collectionView;/**<  */
@property(nonatomic, strong) STButton                     *rightButton;/**<  */

@end

@implementation OEHomeViewController

#pragma mark --vc生命周期
- (void)viewDidLoad{
    [super viewDidLoad];
    __weak typeof(self) weakSelf =  self;
    [self.collectionView registerClass:OEHomeCollectionReusableHeader.class forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    [self.collectionView registerClass:OEHomeCollectionViewCell.class forCellWithReuseIdentifier:@"item"];
    [self.view addSubview:self.collectionView];
    [self.collectionView.mj_header beginRefreshing];
    
    [self st_setLeftItemWithImage:[UIImage imageNamed:@"90×66LOGO"]];
    
    self.rightButton = [[STButton alloc] initWithFrame:CGRectMake(0, 0, 150, 44)
                                                  title:@"定位中"
                                             titleColor:FirstTextColor
                                              titleFont:16
                                           cornerRadius:0
                                        backgroundColor:nil
                                        backgroundImage:nil
                                                  image:[UIImage imageNamed:@"32×34定位"]];
    [self.rightButton setClicAction:^(UIButton *sender) {
        [weakSelf st_rightBarAction:nil];
    }];
    self.rightButton.contentHorizontalAlignment = UIControlContentHorizontalAlignmentRight;
    [self.rightButton makeImageRight];
    [self st_setRightItemWithView:self.rightButton];
    
    NSString * type = @"Fingerprint";
    if (@available(iOS 11.0, *)) {
        if (UIApplication.sharedApplication.delegate.window.safeAreaInsets.bottom) {
            type = @"Face";
        }
    }
    BOOL opened = [[NSUserDefaults standardUserDefaults] boolForKey:OE_FACE_OR_FINGER_PAY_OPEN_KEY];
    if (!opened) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(30 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            NSString * title =  [NSString stringWithFormat:@"You have been detected to support %@ payment",type];
            [self st_showAlertTitle:title message:@"Whether open?" leftTitle:@"Cacnle" rightTitle:@"Set UP" block:^(NSString *name) {
                if ([name isEqualToString:@"Set UP"]) {
                    OEPaymentSettingViewController * vc = OEPaymentSettingViewController.new;
                    [vc.st_currentNavgationController pushViewController:vc animated:YES];
                }
            }];
        });
    }

}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[STLocationManger defult] startUpdatingLocationHande:^(STError *error, CLPlacemark *placemark) {
        [[STLocationManger defult] updatePlacemarkWith:placemark];
        [OEUserDataController sendUpdateLocationRequest];
        NSString * area = [NSString stringWithFormat:@"%@%@",STLocationManger.defult.lastCity,STLocationManger.defult.lastSubLocality];
        [self.rightButton setTitle:area forState:UIControlStateNormal];
        [self.rightButton makeImageRight];
    }];
}
- (void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated{
    [super viewDidDisappear:animated];
}
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * flow = [UICollectionViewFlowLayout new];
        flow.minimumLineSpacing = 9.9;
        flow.minimumInteritemSpacing = 9.9;
        flow.scrollDirection = UICollectionViewScrollDirectionVertical;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, [TMUtils navgationBarBootom], UIScreenWidth, [TMUtils tabBarTop]  - [TMUtils navgationBarBootom]) collectionViewLayout:flow];
        _collectionView.backgroundColor = UIColor.whiteColor;
        _collectionView.delegate = self;
        _collectionView.dataSource = self;

            __weak typeof(self) weakSelf =  self;
        _collectionView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
            [weakSelf sendNetRequest];
        }];
        self.automaticallyAdjustsScrollViewInsets = NO;
        if (ios11) {
            if ([_collectionView respondsToSelector:@selector(setContentInsetAdjustmentBehavior:)]) {
                [_collectionView performSelector:@selector(setContentInsetAdjustmentBehavior:) withObject:@(2) afterDelay:0];
            }
        }
    }
    return _collectionView;
}
#pragma --mark UICollectionViewDataSource
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 2;
}
-(NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    if (section == 0) {
        return self.homeModel.hotBusinessArray.count;
    }
    return self.homeModel.hotOfferArray.count;
}
-(CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.section == 0) {
        CGFloat  itemWith = (UIScreenWidth - 30 )/2;
        return CGSizeMake(itemWith, 200);
    }
    CGFloat  itemWith = (UIScreenWidth - 20);
    return CGSizeMake(itemWith, 125);
}
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    if (section == 0) {
        return UIEdgeInsetsMake(0, 9.9, 0, 9.9);
    }else{
        return UIEdgeInsetsMake(0, 9.9, 0, 9.9);
    }
}
- (UICollectionReusableView*)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath{
    
    OEHomeCollectionReusableHeader * header = [collectionView dequeueReusableSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header" forIndexPath:indexPath];
    header.model = self.homeModel;
    [header bindModel:self.homeModel indexPath:indexPath];
    __weak typeof(self) weakSelf =  self;
    [header.cateButton setClicAction:^(UIButton *sender) {
        [weakSelf onSelctedTypeButtonWithSection:indexPath.section];
    }];
    return header;
    
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section{
    if (section == 0) {
        return CGSizeMake(UIScreenWidth, 240);
    }else{
        return CGSizeMake(UIScreenWidth, 44);
    }
}
-(UICollectionViewCell*)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    OEHomeCollectionViewCell * item =[collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    OEShopEasyModel *model;
    if (indexPath.section == 0) {
        model = self.homeModel.hotBusinessArray[indexPath.row];
        [item st_setBorderWith:0.5 borderColor:TM_lineColor cornerRadius:2];
    }else{
        model = self.homeModel.hotOfferArray[indexPath.row];
        [item st_setBorderWith:0.5 borderColor:UIColor.clearColor cornerRadius:2];
    }
    item.model = model;
    return item;
}
#pragma --mark UICollectionViewDelegate
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    OEShopEasyModel *model;
    if (indexPath.section == 0) {
        model = self.homeModel.hotBusinessArray[indexPath.row];
    }else{
        model = self.homeModel.hotOfferArray[indexPath.row];
    }
    [TMUtils gotoShopHeaderWithModel:model];
    [self.collectionView deselectItemAtIndexPath:indexPath animated:NO];
}
#pragma mark --Action Method
- (void)st_rightBarAction:(id)sender{
    [self.navigationController pushViewController:OELocationViewController.new animated:YES];
}
- (void)onSelctedTypeButtonWithSection:(NSInteger)section{
    if (section == 0) {
        [self.navigationController pushViewController:OEHotBunessViewController.new animated:YES];
    }else{
         [self.navigationController pushViewController:OEHotOfferViewController.new animated:YES];
        
    }
}
#pragma mark --NetWork Method
- (void)sendNetRequest{
    [OEHomeDataController sendGetHomeRequest:^(NSArray * _Nonnull bannerArray, NSArray * _Nonnull hotBusinessArray, NSArray * _Nonnull hotOfferArray) {
        OEHomeModel* model = OEHomeModel.new;
        model.bannerArray = bannerArray;
        model.hotOfferArray = hotOfferArray;
        model.hotBusinessArray = hotBusinessArray;
        self.homeModel = model;
        [self.collectionView.mj_header endRefreshing];
        [self.collectionView reloadData];
    }];
}

@end
